package com.pzl.library;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.ViewPager;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * 页码indicator
 * Created by zl.peng on 2016-03-02.
 */

/**
 * 根据view size 适配字体大小位置
 */
public class PaginationIndicator extends View implements Indicator {
    private static final String TAG = "PaginationIndicator";
    private int mSize = 60;
    private int mPaneColor = Color.parseColor("#fafafa");
    private int mTextColor = Color.parseColor("#c1c1c1");
    private int mProgressColor = Color.parseColor("#f2f2f2");
    private Paint mPaint;
    private ViewPager mViewPager;
    private int mPagerAmount;
    private int mHeight;
    private int mWidth;
    /**
     * 进度条宽度
     */
    private int mProgressStroke = 1;
    /**
     * 进度条宽度适应系数
     */
    private float mProgressStrokeCoefficient = 0.04f;

    private RectF oval;
    private int mCurrentPosition;
    private float mPositionOffset;
    private int mFristTouchDirection = 0;//-1left;1right
    private int mState = 0;//1,2,0
    private boolean mFristTouchFlag = true;
    private int mFristTouchPosition;

    private float mDividerAngle = 90;
    private int mDividerStroke = 2;
    private int mDividerColor = Color.parseColor("#c1c1c1");
    /**
     * 分割线距progress间距
     */
    private int mDividerSpace = 0;
    /**
     * 分割线距progress间距,适应系数
     */
    private float mDividerSpaceCoefficient = 0.05f;
    private TextPaint mTextPaint;
    private int mPositionPending;
    private int mPositionFinal;
    private String mCurrentPage = "1";
    private String mPageTotal;

    /**
     * TextPaint页码字体大小自适应（根据size,页码位数设定）1~5位
     */
    private int[] mAutoTPSizes = new int[5];
    /**
     * 页码总数字体大小
     */
    private int mTotalTextPaintSize;
    /**
     * 当前页码字体大小
     */
    private int mCurrentTextPaintSize;
    /**
     * 当前页码字体大小与总页码数相同
     */
    private int mCopyByTotalTextPaintSize;

    private Rect mRectCurrentPage, mRectTotalPage;
    /**
     * 页码与dividor的间隔，根据size动态设定
     */
    private int mPaginationInterval;
    /**
     * 页码间隔系数
     */
    private float mPaginationIntervalCoefficient = 0.08f;

    public PaginationIndicator(Context context) {
        this(context, null);
    }

    public PaginationIndicator(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PaginationIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PaginationIndicator, 0, 0);
        mSize = (int) ta.getDimension(R.styleable.PaginationIndicator_Size, 60);
        mPaneColor = ta.getColor(R.styleable.PaginationIndicator_PaneColor, Color.parseColor("#fafafa"));
        mTextColor = ta.getColor(R.styleable.PaginationIndicator_TextColor, Color.parseColor("#b6b6b6"));
        mProgressColor = ta.getColor(R.styleable.PaginationIndicator_ProgressColor, Color.parseColor("#ef1515"));

        ta.recycle();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);

        initTextPaintSizes();
        mProgressStroke = (int) (mSize * mProgressStrokeCoefficient) < 1 ? 1 : (int) (mSize * mProgressStrokeCoefficient);
        mRectTotalPage = new Rect();
        mRectCurrentPage = new Rect();
        mPaginationInterval = (int) (mSize * mPaginationIntervalCoefficient);
        mDividerSpace = (int) (mSize * mDividerSpaceCoefficient);
    }

    /**
     * 初始化字体大小自适应系数(1~5位)
     * 可尝试差值为0.03的自适应系数
     */
    private void initTextPaintSizes() {
        mAutoTPSizes[0] = (int) (mSize * 0.4f);//1位数
        mAutoTPSizes[1] = (int) (mSize * 0.37f);//2位数
        mAutoTPSizes[2] = (int) (mSize * 0.32f);//3位数
        mAutoTPSizes[3] = (int) (mSize * 0.29f);//4位数
        mAutoTPSizes[4] = (int) (mSize * 0.26f);//5位数
    }

    @Override
    public void bindViewPager(ViewPager viewPager) {
        if (viewPager == null) throw new IllegalStateException("viewpager is null!");
        if (viewPager.getAdapter() == null)
            throw new IllegalStateException("please set viewpager adapter!");
        mViewPager = viewPager;
        mViewPager.addOnPageChangeListener(this);
        mPagerAmount = mViewPager.getAdapter().getCount();
        mPageTotal = Integer.toString(mPagerAmount);
        mTotalTextPaintSize = mAutoTPSizes[mPageTotal.length() - 1];//初始化总页数字体大小
        mCopyByTotalTextPaintSize = mTotalTextPaintSize;//字体size副本
        mCurrentTextPaintSize = mAutoTPSizes[0];//初始化当前页码字体大小,默认1位
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        Log.i(TAG, "positionOffsetPixels=" + positionOffsetPixels);
        mCurrentPosition = position;
        mPositionOffset = positionOffset;
        if (mFristTouchFlag == true && mState == 1 && positionOffsetPixels <= mViewPager.getWidth() / 2) {
            mFristTouchDirection = -1;
            mFristTouchPosition = position;
            mFristTouchFlag = false;
        } else if (mFristTouchFlag == true && mState == 1 && positionOffsetPixels > mViewPager.getWidth() / 2 && positionOffsetPixels <= mViewPager.getWidth()) {
            mFristTouchDirection = 1;
            mFristTouchPosition = position;
            mFristTouchFlag = false;
        }
        invalidate();
    }

    @Override
    public void onPageSelected(int position) {
        mPositionPending = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        Log.i(TAG, "state=" + state);
        mState = state;
        if (state == 0) {
            mPositionFinal = mPositionPending;
            mCurrentPage = Integer.toString(mPositionFinal + 1);
            mCurrentTextPaintSize = mAutoTPSizes[mCurrentPage.length() - 1];//当前页码字体大小
            mFristTouchFlag = true;
            invalidate();
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int width, height;
        if (mViewPager == null || widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {
            width = getPaddingLeft() + mSize + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(width, widthSize);
            }
        }

        if (mViewPager == null || heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            height = getPaddingTop() + mSize + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightSize);
            }
        }
        setMeasuredDimension(width, height);

    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mHeight = getMeasuredHeight();
        mWidth = getMeasuredWidth();
        oval = new RectF(mWidth / 2 - mSize / 2 + mProgressStroke / 2, mHeight / 2 - mSize / 2 + mProgressStroke / 2, mWidth / 2 + mSize / 2 - mProgressStroke / 2, mHeight / 2 + mSize / 2 - mProgressStroke / 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mPagerAmount <= 0) return;

        mPaint.setColor(mPaneColor);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(mWidth / 2, mHeight / 2, mSize / 2, mPaint);

        /**
         * pagination draw
         */

        mTextPaint.setColor(mTextColor);

        mTextPaint.getTextBounds(mCurrentPage, 0, mCurrentPage.length(), mRectCurrentPage);
        mTextPaint.getTextBounds(mPageTotal, 0, mPageTotal.length(), mRectTotalPage);

        mTextPaint.setTextSize(mCopyByTotalTextPaintSize);
        canvas.drawText(mCurrentPage, mWidth / 2 - (mRectCurrentPage.right - mRectCurrentPage.left) / 2, mHeight / 2 - mPaginationInterval, mTextPaint);
        mTextPaint.setTextSize(mTotalTextPaintSize);
        canvas.drawText(mPageTotal, mWidth / 2 - (mRectTotalPage.right - mRectTotalPage.left) / 2, mHeight / 2 + (mRectTotalPage.bottom - mRectTotalPage.top) + mPaginationInterval, mTextPaint);

        mPaint.setColor(mDividerColor);
        mPaint.setStrokeWidth(mDividerStroke);
        canvas.save();
        canvas.rotate(mDividerAngle, mWidth / 2, mHeight / 2);
        canvas.drawLine(mWidth / 2, mHeight / 2 - mSize / 2 + mProgressStroke + mDividerSpace, mWidth / 2, mHeight / 2 + mSize / 2 - mProgressStroke - mDividerSpace, mPaint);
        canvas.restore();


        /**
         * progress draw
         */
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mProgressStroke);
        mPaint.setColor(mProgressColor);
        if (mState != 0) {//非停止状态
            if (mFristTouchDirection == -1) {//初始左划
                if (mCurrentPosition != mFristTouchPosition) {
                    canvas.drawArc(oval, -90, -360 * (1 - mPositionOffset), false, mPaint);//初始左划小段后强制右划上个pos
                } else {
                    canvas.drawArc(oval, -90, 360 * mPositionOffset, false, mPaint);//常态
                }
            } else if (mFristTouchDirection == 1) {//初始右划
                if (mPositionOffset == 0) return;//过滤回弹时positionOffsetPixels=0
                if (mCurrentPosition != mFristTouchPosition) {
                    canvas.drawArc(oval, -90, 360 * mPositionOffset, false, mPaint);//初始右划小段后强制左划下个pos
                } else {
                    canvas.drawArc(oval, -90, -360 * (1 - mPositionOffset), false, mPaint);//常态
                }
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mViewPager == null) return;
        mViewPager.removeOnPageChangeListener(this);
    }
}
